<template>
  <div class="container">
    <el-container style="height: 800px; border: 2px #eee">
        <el-header style="height:100px">
        <img class="logo" alt="logo" :src="require('./../../assets/logo1.png')"/>
            <div class="avator" style="text-align: right; float:right">
                <div>
                <el-avatar :size="65" src="https://ftp.bmp.ovh/imgs/2021/06/8691b8db5223ac81.jpg"></el-avatar>
                </div>
            </div>
        </el-header>
            <div class="container1" style="background-color: rgb(255,255,255);">
                <el-row type="flex" align="middle" justify="justify">
                    <el-col :offset="1" :span="4">
                        <el-button size="mini" round @click="$router.push({path: '/admin/home'})">
                            <i class="el-icon-arrow-left"/>
                        </el-button>
                    </el-col>
                    <el-col :span="10" :offset="3">
                        <el-menu :default-actice="activeIndex" class="el-menu" mode="horizontal" @select="handleSelect" style="border: hidden"> 
                            <el-menu-item index="1" style="margin-left:60px">编辑</el-menu-item>
                            <el-menu-item index="2" style="margin-left:50px">发布</el-menu-item>
                            <el-menu-item index="3" style="margin-left:50px">统计</el-menu-item>
                        </el-menu>
                    </el-col>
                </el-row>
            </div>
    </el-container>
    
    
    <div class="left-board">
      <el-scrollbar class="left-scrollbar">
        <div class="components-list">
          <div v-for="(item, listIndex) in leftComponents" :key="listIndex">
            <div class="components-title">
              <svg-icon icon-class="component" />
              {{ item.title }}
            </div>
            <draggable
              class="components-draggable"
              :list="item.list"
              :group="{ name: 'componentsGroup', pull: 'clone', put: false }"
              :clone="cloneComponent"
              draggable=".components-item"
              :sort="false"
              @end="onEnd"
            >
              <div
                v-for="(element, index) in item.list"
                :key="index"
                class="components-item"
                @click="addComponent(element)"
              >
                <div class="components-body">
                  <svg-icon :icon-class="element.__config__.tagIcon" />
                  {{ element.__config__.label }}
                </div>
              </div>
            </draggable>
          </div>
        </div>
      </el-scrollbar>
    </div>

    <div class="center-board">
      <el-scrollbar class="center-scrollbar">
        <el-row class="center-board-row" v-if="formConf" :gutter="formConf.gutter">
          <el-row type="flex" justify="center" align="middle">
            <el-col :span="20" style="text-align:center">
            <h4 class="form-name-text" contenteditable="true" @blur="(event)=>{
              this.formConf.title=event.target.innerText
              this.saveProjectInfo() 
              }"> {{formConf.title}} </h4>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" align="middle">
            <el-col :span="20" >
            <span class="form-name-text" contenteditable="true" @blur="(event)=>{
                  this.formConf.description=event.target.innerText
                  this.saveProjectInfo()
              }">
              {{ formConf.description }}
            </span>
            </el-col>
          </el-row>
          <el-divider></el-divider>
          <el-form
            :size="formConf.size"
            :label-position="formConf.labelPosition"
            :disabled="formConf.disabled"
            :label-width="formConf.labelWidth + 'px'"
          >
            <draggable class="drawing-board" :list="drawingList" :animation="340" group="componentsGroup" @end="onItemEnd">
              <draggable-item
                v-for="(item, index) in drawingList"
                :key="item.renderKey"
                :drawing-list="drawingList"
                :current-item="item"
                :index="index"
                :active-id="activeId"
                :form-conf="formConf"
                @activeItem="activeFormItem"
                @copyItem="drawingItemCopy"
                @deleteItem="drawingItemDelete"
              />
            </draggable>
            <div v-show="!drawingList.length" class="empty-info">
              从左侧拖入或点选组件进行表单设计
            </div>
          </el-form>
        </el-row>
      </el-scrollbar>
    </div>

    <right-panel
      :active-data="activeData"
      :form-conf="formConf"
      :show-field="!!drawingList.length"
      @tag-change="tagChange"
      @data-change="updateProjectItemInfo"
    />
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import { debounce } from 'throttle-debounce'
import render from '@/components/render/render'
import RightPanel from './RightPanel'
import {
  inputComponents, selectComponents, layoutComponents, formConf
} from '@/components/generator/config'
import {
  exportDefault, beautifierConf, isNumberStr, titleCase, deepClone, isObjectObject
} from '@/utils/index'
import {dbDataConvertForItemJson, formItemConvertData} from '@/utils/convert'
import drawingDefalut from '@/components/generator/drawingDefalut'
import DraggableItem from './DraggableItem'
import {
  getDrawingList, saveDrawingList, getIdGlobal, saveIdGlobal, getFormConf
} from '@/utils/db'
import {postKeyValueRequest,postRequest,getRequest} from '@/api/api'
let oldActiveId
let tempActiveData
const idGlobal = getIdGlobal()

export default {
  components: {
    draggable,
    render,
    RightPanel,
    DraggableItem
  },
  data() {
    return {
      activeIndex:'1',
      idGlobal,
      formConf: null,
      inputComponents,
      selectComponents,
      labelWidth: 100,
      drawingList: drawingDefalut,
      drawingData: {},
      activeId: drawingDefalut.length != 0 ? drawingDefalut[0].formId : 0,
      formTitleData: {
        projectKey: "",
        title: "",
        describes: ""
      },
      activeData: drawingDefalut ? drawingDefalut[0] : null,
      saveDrawingListDebounce: debounce(340, saveDrawingList),
      saveIdGlobalDebounce: debounce(340, saveIdGlobal),
      leftComponents: [
        {
          title: '输入型组件',
          list: inputComponents
        },
        {
          title: '选择型组件',
          list: selectComponents
        }
      ]
    }
  },
  computed: {
  },
  watch: {
    'activeData.__config__.label': function (val, oldVal) {
      if (
        this.activeData.placeholder === undefined
        || !this.activeData.__config__.tag
        || oldActiveId !== this.activeId
      ) {
        return
      }
      this.activeData.placeholder = this.activeData.placeholder.replace(oldVal, '') + val
    },
    activeId: {
      handler(val) {
        oldActiveId = val
      },
      immediate: true
    },
    drawingList: {
      handler(val) {
        this.saveDrawingListDebounce(val)
        if (val.length === 0) this.idGlobal = 100
      },
      deep: true
    },
    idGlobal: {
      handler(val) {
        this.saveIdGlobalDebounce(val)
      },
      immediate: true
    }
  },
  mounted() {
      this.formConf = JSON.parse(JSON.stringify(formConf))
      //全局组件Id
      getRequest(`/project/item/max-form-id`, {params: {key: this.$route.query.key}}).then(res => {
          console.log(res)
           this.idGlobal = res.data ? res.data : 100
      })
      this.drawingList = []
      
  },
  methods: {
    saveProjectInfo: debounce(430, true, function() {
        this.formTitleData.projectKey = this.$route.query.key
        this.formTitleData.title = this.formConf.title
        this.formTitleData.describes = this.formConf.description
         postKeyValueRequest('/project/update', this.formTitleData).then((res) => {
              console.log(res)
         })
    }),
    updateProjectItemInfo(val) {
        let data = formItemConvertData(val, this.$route.query.key)
        console.log(data)
        postRequest('/project/item/update',data).then(resp=>{
          
        })
    },
    deleteProjectItemInfo(val) {
        let data = formItemConvertData(val, this.$route.query.key)
        postRequest('/project/item/delete', data).then((res) => {
          console.log(res)
        })
    },
    saveProjectItemInfo(item) {
        let params = formItemConvertData(item, this.$route.query.key)
        postRequest('/project/item/create', params).then(res => {
            item.sort = res.data.sort
        })
    },
    setLoading(component, val) {
      const { directives } = component
      if (Array.isArray(directives)) {
        const t = directives.find(d => d.name === 'loading')
        if (t) t.value = val
      }
    },
    activeFormItem(currentItem) {
      this.activeData = currentItem
      this.activeId = currentItem.__config__.formId
    },
    onEnd(obj) {
      if (obj.from !== obj.to) {
        // this.fetchData(tempActiveData)
        this.activeData = tempActiveData
        this.activeId = this.idGlobal
      }
      this.onItemEnd(obj)
    },
    onItemEnd(obj) {
      let params = {'projectKey': this.$route.query.key}
      if (this.drawingList[obj.newIndex - 1]) {
          let sort1 = this.drawingList[obj.newIndex - 1].sort
          params.beforePosition = sort1
      }
      if (this.drawingList[obj.newIndex + 1]) {
          let sort2 = this.drawingList[obj.newIndex + 1].sort
          params.afterPosition = sort2
      }
      params.formItemId = this.drawingList[obj.newIndex].__config__.formId
    },
    addComponent(item) {
      const clone = this.cloneComponent(item)
      // this.fetchData(clone)
      this.drawingList.push(clone)
      this.activeFormItem(clone)
    },
    cloneComponent(origin,save=true) {
      const clone = deepClone(origin)
      const config = clone.__config__
      config.span = this.formConf.span // 生成代码时，会根据span做精简判断
      this.createIdAndKey(clone)
      clone.placeholder !== undefined && (clone.placeholder += config.label)
      tempActiveData = clone
      if (save) {
          this.saveProjectItemInfo(clone)
      }
      return tempActiveData
    },
    createIdAndKey(item) {
      const config = item.__config__
      config.formId = ++this.idGlobal
      config.renderKey = `${config.formId}${+new Date()}` // 改变renderKey后可以实现强制更新组件
      if (config.layout === 'colFormItem') {
        item.__vModel__ = `field${this.idGlobal}`
      } else if (config.layout === 'rowFormItem') {
        config.componentName = `row${this.idGlobal}`
        !Array.isArray(config.children) && (config.children = [])
        delete config.label // rowFormItem无需配置label属性
      }
      if (Array.isArray(config.children)) {
        config.children = config.children.map(childItem => this.createIdAndKey(childItem))
      }
      return item
    },
    drawingItemCopy(item, list) {
      let clone = deepClone(item)
      clone = this.createIdAndKey(clone)
      list.push(clone)
      this.activeFormItem(clone)
      this.saveProjectItemInfo(clone)
    },
    drawingItemDelete(index, list) {
      let item = list[index]
      list.splice(index, 1)
      this.$nextTick(() => {
          const len = this.drawingList.length
          if (len) {
              this.activeFormItem(this.drawingList[len - 1])
          }
      })
      this.deleteProjectItemInfo(item)
    },
    tagChange(newTag) {
      newTag = this.cloneComponent(newTag)
      const config = newTag.__config__
      newTag.__vModel__ = this.activeData.__vModel__
      config.formId = this.activeId
      config.span = this.activeData.__config__.span
      this.activeData.__config__.tag = config.tag
      this.activeData.__config__.tagIcon = config.tagIcon
      this.activeData.__config__.document = config.document
      this.activeData.typeId = newTag.typeId
      if (typeof this.activeData.__config__.defaultValue === typeof config.defaultValue) {
        config.defaultValue = this.activeData.__config__.defaultValue
      }
      Object.keys(newTag).forEach(key => {
        if (this.activeData[key] !== undefined) {
          newTag[key] = this.activeData[key]
        }
      })
      this.activeData = newTag
      this.updateProjectItemInfo(newTag)
      this.updateDrawingList(newTag, this.drawingList)
    },

    updateDrawingList(newTag, list) {
      const index = list.findIndex(item => item.__config__.formId === this.activeId)
      if (index > -1) {
        list.splice(index, 1, newTag)
      } else {
        list.forEach(item => {
          if (Array.isArray(item.__config__.children)) this.updateDrawingList(newTag, item.__config__.children)
        })
      }
    },
    handleSelect(key,keyPath){
        var url = window.location.href;
        var keys = url.split('=')[1];
        if(key == 1){
          location.reload()
        }else if(key == 2){
          this.$router.push({path: '/admin/publish', query: {key: keys}})
        }else if(key == 3){
          this.$router.push({path: '/admin/statistics', query: {key: keys}})
        }
    }
  }
}
</script>

<style lang='scss'>
@import '@/styles/home';
</style>
